package com.zsl.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class MyEcdFilter implements Filter {
    private FilterConfig filterConfig;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器被创建~~~");
        this.filterConfig = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String encode = this.filterConfig.getInitParameter("encode");

        request.setCharacterEncoding(encode);
        response.setContentType("text/html;charset=" + encode);

        MyHttpServletRequest myrequest = new MyHttpServletRequest(request);

        filterChain.doFilter(myrequest, response);
    }

    @Override
    public void destroy() {
        System.out.println("过滤器被销毁~~~");
    }

    public static String encode(String str) {
        String newString = "";
        try {
            newString = new String(str.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            // 把iso-8859-1 转换成 utf-8
        }
        return newString;
    }

    public static class MyHttpServletRequest extends HttpServletRequestWrapper {

        private final HttpServletRequest request;

        public MyHttpServletRequest(HttpServletRequest request) {

            super(request);
            this.request = request;

        }

        public String getParameter(String name) {
            String value = super.getParameter(name);
            if (value == null)
                return null;
            if ("get".equalsIgnoreCase(request.getMethod())) {
                try {
                    value = new String(value.getBytes(StandardCharsets.ISO_8859_1), request.getCharacterEncoding());
                } catch (Exception e) {
                    e.printStackTrace();
                    // 把iso-8859-1 转换成 utf-8
                }
            }
            return value;
        }
    }
}
